import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_weight_parser/flutter_weight_parser.dart';
import 'package:flutter_weight_parser/stream/WeightStream.dart';

void main() {
  runApp(MyApp());
}

String HEX_DATA =
    "2 2b 30 30 38 37 32 39 33 31 43 3 0 1 ff fe";

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      var datas = HEX_DATA.split(" ").map((e) => int.parse(e, radix: 16));

      var protocols = await FlutterWeightParser.loadProtocols("https://gitee.com/scvzerng/pro-test/raw/master/WeightProtocols.js");
      print(protocols);
      print(datas);
      // bool isRun = false;
      WeightStream stream = new WeightStream();
      Timer.periodic(Duration(milliseconds: 100), (timer) async {
        for (var d in datas) {
          stream.push(d);
        }
      });

      stream.stream.listen((byte) async {
        for (var p in protocols!) {

          var weight = await FlutterWeightParser.addAndParseWeight("1", p, byte);
          if (weight != null) {
            print("分组1 $p  重量 $weight");
          }
          weight = await FlutterWeightParser.addAndParseWeight("2", p, byte);
          if (weight != null) {
            print("分组2 $p  重量 $weight");
          }

        }
      });

    } on PlatformException {
    }


    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text('Running on: $_platformVersion\n'),
        ),
      ),
    );
  }
}

